package cn.iocoder.yudao.module.liveprice.service.message.impl;

import cn.iocoder.yudao.module.liveprice.api.message.PriceMessageHandler;
import cn.iocoder.yudao.module.liveprice.api.message.impl.StockPriceMessage;
import cn.iocoder.yudao.module.liveprice.service.price.PriceCacheService;
import cn.iocoder.yudao.module.liveprice.websocket.PriceWebSocketManager;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 股票价格消息处理器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class StockPriceMessageHandler implements PriceMessageHandler<StockPriceMessage> {

    private final PriceWebSocketManager webSocketManager;
    private final PriceCacheService priceCacheService;
    private final ObjectMapper objectMapper;

    @Override
    public String getMessageType() {
        return "STOCK_PRICE";
    }

    @Override
    public void handleMessage(StockPriceMessage message) {
        try {
            // 1. 更新缓存
            priceCacheService.updatePrice(message.getSymbol(), message);
            
            // 2. 推送到WebSocket
            String messageJson = objectMapper.writeValueAsString(message);
            webSocketManager.sendMessageToTopic("stock." + message.getSymbol(), messageJson);
            
            log.info("处理股票价格消息: {}", message.getSymbol());
        } catch (Exception e) {
            log.error("处理股票价格消息失败", e);
        }
    }
} 